<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>药品入库</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
        v-loading="loading"
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="选择药品" prop="drugId">
              <el-select 
                v-model="form.drugId" 
                placeholder="请选择药品" 
                filterable 
                remote 
                :remote-method="searchDrugs"
                :loading="drugsLoading"
                @change="handleDrugChange"
                style="width: 100%"
              >
                <el-option 
                  v-for="item in drugOptions" 
                  :key="item.id" 
                  :label="`${item.name} (${item.specification})`" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="药品编码">
              <el-input v-model="drugInfo.code" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="药品分类">
              <el-input v-model="drugInfo.category" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="生产厂家">
              <el-input v-model="drugInfo.manufacturer" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="规格">
              <el-input v-model="drugInfo.specification" disabled />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="当前库存">
              <el-input v-model="drugInfo.inventory" disabled>
                <template #append>{{ drugInfo.unit }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">入库信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="入库数量" prop="quantity">
              <el-input-number 
                v-model="form.quantity" 
                :min="1" 
                :step="1" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="采购单价(元)" prop="purchasePrice">
              <el-input-number 
                v-model="form.purchasePrice" 
                :precision="2" 
                :step="0.1" 
                :min="0" 
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="生产日期" prop="productionDate">
              <el-date-picker 
                v-model="form.productionDate" 
                type="date" 
                placeholder="选择生产日期" 
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="有效期至" prop="expiryDate">
              <el-date-picker 
                v-model="form.expiryDate" 
                type="date" 
                placeholder="选择有效期" 
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplier">
              <el-input v-model="form.supplier" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio label="purchase">采购入库</el-radio>
                <el-radio label="return">退货入库</el-radio>
                <el-radio label="adjustment">调整入库</el-radio>
                <el-radio label="other">其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="入库日期" prop="purchaseDate">
              <el-date-picker 
                v-model="form.purchaseDate" 
                type="date" 
                placeholder="选择入库日期" 
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="请输入备注信息" 
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { drugAPI, drugInventoryAPI } from '@/utils/api'

const router = useRouter()
const route = useRoute()
const drugIdFromQuery = route.query.drugId || ''

// 表单数据
const formRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const drugsLoading = ref(false)
const drugOptions = ref([])

// 药品信息
const drugInfo = reactive({
  code: '',
  name: '',
  category: '',
  manufacturer: '',
  specification: '',
  inventory: 0,
  unit: ''
})

// 表单数据
const form = reactive({
  drugId: drugIdFromQuery,
  batchNumber: '',
  quantity: 1,
  purchasePrice: 0,
  productionDate: '',
  expiryDate: '',
  supplier: '',
  type: 'purchase',
  purchaseDate: new Date().toISOString().split('T')[0],
  remark: ''
})

// 表单验证规则
const rules = {
  drugId: [
    { required: true, message: '请选择药品', trigger: 'change' }
  ],
  batchNumber: [
    { required: true, message: '请输入批次号', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '入库数量必须大于0', trigger: 'blur' }
  ],
  purchasePrice: [
    { required: true, message: '请输入采购单价', trigger: 'blur' }
  ],
  productionDate: [
    { required: true, message: '请选择生产日期', trigger: 'change' }
  ],
  expiryDate: [
    { required: true, message: '请选择有效期', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择入库类型', trigger: 'change' }
  ],
  purchaseDate: [
    { required: true, message: '请选择入库日期', trigger: 'change' }
  ]
}

// 监听药品ID变化
watch(() => form.drugId, (newVal) => {
  if (newVal) {
    fetchDrugDetail(newVal)
  } else {
    // 清空药品信息
    Object.keys(drugInfo).forEach(key => {
      drugInfo[key] = key === 'inventory' ? 0 : ''
    })
  }
})

// 搜索药品
const searchDrugs = async (query) => {
  if (query.length < 1) return
  
  drugsLoading.value = true
  try {
    const params = {
      name: query,
      status: '启用',
      limit: 20
    }
    
    const res = await drugAPI.getDrugs(params)
    if (res.data && res.data.success) {
      drugOptions.value = res.data.data.drugs || []
    }
  } catch (error) {
    console.error('搜索药品失败', error)
  } finally {
    drugsLoading.value = false
  }
}

// 处理药品选择变化
const handleDrugChange = (drugId) => {
  if (drugId) {
    fetchDrugDetail(drugId)
  }
}

// 获取药品详情
const fetchDrugDetail = async (drugId) => {
  loading.value = true
  try {
    const res = await drugAPI.getDrug(drugId)
    
    if (res.data && res.data.success) {
      const drug = res.data.data.drug
      
      // 填充药品信息
      drugInfo.code = drug.code || ''
      drugInfo.name = drug.name || ''
      drugInfo.category = drug.category || ''
      drugInfo.manufacturer = drug.manufacturer || ''
      drugInfo.specification = drug.specification || ''
      drugInfo.inventory = drug.inventory || 0
      drugInfo.unit = drug.unit || ''
      
      // 设置默认采购价格
      form.purchasePrice = drug.price || 0
    } else {
      ElMessage.error(res.data.message || '获取药品详情失败')
    }
  } catch (error) {
    console.error('获取药品详情失败', error)
    ElMessage.error('获取药品详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 验证日期
    const productionDate = new Date(form.productionDate)
    const expiryDate = new Date(form.expiryDate)
    const purchaseDate = new Date(form.purchaseDate)
    const today = new Date()
    
    if (expiryDate <= productionDate) {
      ElMessage.error('有效期必须大于生产日期')
      return
    }
    
    if (expiryDate <= today) {
      ElMessage.warning('该药品已过期，确定要入库吗？')
    }
    
    submitting.value = true
    try {
      // 准备提交的数据
      const inventoryData = {
        drugId: form.drugId,
        batchNumber: form.batchNumber,
        quantity: form.quantity,
        purchasePrice: form.purchasePrice,
        productionDate: form.productionDate,
        expiryDate: form.expiryDate,
        supplier: form.supplier,
        type: form.type,
        purchaseDate: form.purchaseDate,
        remark: form.remark
      }
      
      const res = await drugInventoryAPI.createInventory(inventoryData)
      
      if (res.data && res.data.success) {
        ElMessage.success('药品入库成功')
        goBack()
      } else {
        ElMessage.error(res.data.message || '药品入库失败')
      }
    } catch (error) {
      console.error('药品入库失败', error)
      ElMessage.error('药品入库失败')
    } finally {
      submitting.value = false
    }
  })
}

// 返回上一页
const goBack = () => {
  router.push('/drugs/inventory')
}

// 初始化
const init = async () => {
  // 如果URL中有drugId参数，则直接获取药品详情
  if (form.drugId) {
    // 获取并添加到选项中
    try {
      const res = await drugAPI.getDrug(form.drugId)
      if (res.data && res.data.success) {
        const drug = res.data.data.drug
        drugOptions.value = [drug]
      }
    } catch (error) {
      console.error('获取药品详情失败', error)
    }
  }
}

// 生命周期钩子
onMounted(() => {
  init()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}
</style> 